package sz1;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LoggingInvocationHandler implements InvocationHandler {
    private final Object target;

    public LoggingInvocationHandler(Object target) {
        this.target = target;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Method methodTarget = this.target.getClass().getMethod(method.getName());
        if (methodTarget.isAnnotationPresent(Log.class)) {
            String methodName = method.getName();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
            LocalDateTime startTime = LocalDateTime.now();
            System.out.println("[LOG]Method:" + methodName + "started at:" + startTime.format(formatter));
            Object result = method.invoke(this.target, args);
            LocalDateTime endTime = LocalDateTime.now();
            long duration = Duration.between(startTime, endTime).toMillis();
            System.out.println("[LOG]Method:" + methodName + "ended at:" + endTime.format(formatter));
            System.out.println("[LOG]Method:" + methodName + "executed in:" + duration + "ms");
            return result;
        } else {
            return method.invoke(this.target, args);
        }
    }
}
